package com.techysky.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.techysky.entity.DataModule;
import com.techysky.entity.Paper;
import com.techysky.entity.PublicModule;
import com.techysky.entity.Question;
import com.techysky.entity.QuestionList;
import com.techysky.entity.QuestionModel;
import com.techysky.entity.User;
import com.techysky.repository.DataModuleRepository;
import com.techysky.repository.QuestionRepository;
import com.techysky.service.PublicModuleService;
import com.techysky.service.QuestionService;
@Controller
@RequestMapping("/questions")
public class QuestionController{
	@Resource
	private QuestionService questionService;
	
	@Autowired
	private DataModuleRepository dataModuleRepository;
	@Autowired
	private PublicModuleService publicModuleService;
	@Autowired
	private QuestionRepository questionRepository;
	@RequiresPermissions("sys:testquestions:testquestions")
	@RequestMapping("/questions")
	public String questions() {
		
		return "questions";
	}
	
	@RequiresPermissions("sys:testquestions:view")
	@RequestMapping(value = "/findByPage")
	@ResponseBody
	public Object operator(int pageNo, int pageSize,HttpServletRequest request) {
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter("search");
		Page<Question> qs=questionService.findByPage(pageable,search);
		List<Question> questionlist=qs.getContent();
		for (int i = 0; i <questionlist.size(); i++) {
			if(!questionlist.get(i).getQuestionPaper().isEmpty()){
				questionlist.get(i).setStatus("0");//被占用
			}else{
				questionlist.get(i).setStatus("1");
			}
		}
		return questionlist;
	}
	/**
	 * 验证试题名称唯一性
	 * 
	 */	
	@RequestMapping(value = "/questionNameCheck")
	@ResponseBody
	public Object  questionNameCheck(String t_questionname) {
		List<Question> questionSize =  questionRepository.findByContent(t_questionname);
		return questionSize;
	}

	@RequiresPermissions("sys:testquestions:add")
	@RequestMapping("/questions-add")
	public String questionsadd(Model model) {
		List<PublicModule> pms = null;//publicModuleService.findByParentId(null);
		model.addAttribute("pmrows", pms);
		return "questions-add";
	}
	/**
	 * 删除验证页
	 * 
	 */
	@RequestMapping("/deleteAlert")
	public String deleteAlert() {
		return "deleteAlert";
	}
	
	
	@RequestMapping(value="/saveQuestion",method=RequestMethod.POST)
	@ResponseBody
	public  String saveQuestion(@ModelAttribute("question") Question question,HttpServletRequest request) {
		Map<String, String[]> map=request.getParameterMap();
		
		String dmhidden=request.getParameter("dataModelhidden");
		String[] dmh=map.get("dataModelhidden[]");
		if(dmh!=null){
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < dmh.length; i++){
				 sb. append(dmh[i]+",");
			}
			String dmhstr = sb.toString();
			question.setDataModelId(dmhstr);
		}else{
			question.setDataModelId(dmhidden);
		}
		String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 
		question.setCreateDate(getSystemTime);
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		question.setCreateUser(user.getUserName());
		this.questionService.save(question);
		return "1";
	}
	
	@RequestMapping(value="/updateQuestion",method=RequestMethod.POST)
	@ResponseBody
	public  String updateQuestion(@ModelAttribute("question") Question question,HttpServletRequest request,String answers) {
		Map<String, String[]> map=request.getParameterMap();
		if (null==question.getAnswer()) {
			String[] answ=map.get("answers[]");
			
			if(answ!=null){
				StringBuilder sb = new StringBuilder();
				for(int i = 0; i < answ.length; i++){
					 sb. append(answ[i]);
				}
				String answer = sb.toString();
				question.setAnswer(answer);
			}else{
				question.setAnswer(answers);
			}
		}
		String dmhidden=request.getParameter("dataModelhidden");
		String[] dmh=map.get("dataModelhidden[]");
		questionService.deleteModelByQid(question.getId());
		if(dmh!=null){
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < dmh.length; i++){
				 sb. append(dmh[i]+",");
			}
			String dmhstr = sb.toString();
			question.setDataModelId(dmhstr);
		}else{
			question.setDataModelId(dmhidden);
		}
		String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 
		question.setCreateDate(getSystemTime);
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		question.setCreateUser(user.getUserName());
		questionService.save(question);
		return "1";
	}
	@RequiresPermissions("sys:testquestions:del")
	@RequestMapping(value="/delQuestions")
	@ResponseBody
	public String delQuestions(String ids) {
		return questionService.deleteQuestions(ids);
	}
	
	@RequestMapping(value="/selQuestions",method=RequestMethod.POST)
	@ResponseBody 
	public QuestionList  selQuestions(@ModelAttribute("paper") Paper paper) {
		
		return questionService.findQuestionByRandom(paper);
	}
	@RequestMapping(value="/selQuestionsByIds",method=RequestMethod.POST)
	@ResponseBody 
	public QuestionList  selQuestionsByIds(String qids) {
		return questionService.findQuestionByIds(qids);
	}
	@RequiresPermissions("sys:testquestions:edit")
	@RequestMapping("/questions-edit")
	public ModelAndView questionsedit(String id) {
		List<PublicModule> pms = null;//publicModuleService.findByParentId(null);
		Question question=questionService.findById(id);
		List<DataModule> dms=new ArrayList<>();
		 List<QuestionModel> qms=questionService.findModelByQuestionId(question.getId());
		if(qms!=null&&!qms.isEmpty()){
			for(int i=0;i<qms.size();i++){
				DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());							
				dms.add(dm);
			}
		}
		ModelAndView mv=new ModelAndView();
		mv.setViewName("questions-edit");
		mv.addObject("question", question);
		mv.addObject("dms", dms);
		mv.addObject("pmrows", pms);
		return mv;
	}
}
